<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.name" placeholder="部门姓名"></el-input>
                </el-form-item>

                <el-select v-model="filters.state" placeholder="请选择状态">
                    <el-option label="全部" value=""></el-option>
                    <el-option label="启用" value="1"></el-option>
                    <el-option label="禁用" value="0"></el-option>
                </el-select>

                <el-form-item>
                    <el-button type="primary" v-on:click="getSuperDepartment">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="department" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" label="排序" width="80">
            </el-table-column>
            <el-table-column prop="id" label="编号" width="120" sortable>
            </el-table-column>
            <el-table-column prop="sn" label="部门编号" width="120" sortable>
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="120" sortable>
            </el-table-column>
            <el-table-column prop="state" label="状态" width="100" :formatter="formatState"  sortable>
            </el-table-column>

            <el-table-column prop="manager.username" label="部门经理" width="120" sortable>
            </el-table-column>
            <el-table-column prop="parent.name" label="上级部门" width="120" sortable>
            </el-table-column>

            <el-table-column label="操作" width="150">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
            </el-pagination>
        </el-col>
        <!--新增框-->
        <el-dialog title="添加" :visible.sync="dialogVisible" width="30%" >
            <el-form  :model="addform" :rules="addformrules" class="demo-form-inline" ref="addform">
                <el-form-item label="部门编号" prop="sn">
                    <el-input v-model="addform.sn" placeholder="部门编号"></el-input>
                </el-form-item>

                <el-form-item label="部门名" prop="name">
                    <el-input v-model="addform.name" placeholder="部门名"></el-input>
                </el-form-item>

                <el-form-item label="部门经理">
                    <el-select v-model="addform.managerId" placeholder="请选择">
                        <el-option
                                v-for="item in managerDepartmentOptions"
                                :key="item.id"
                                :label="item.username"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="上级部门">
                    <el-select v-model="addform.parentId" placeholder="请选择">
                        <el-option
                                v-for="item in parentDepartmentOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>


                <el-form-item label="状态" >
                    <el-radio-group v-model="addform.state" >
                        <el-radio  value="开启" :label=1>开启</el-radio>
                        <el-radio  value="禁用" :label=0>禁用</el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary"@click.native="addSubmit" :loading="addLoading">确 定</el-button>
            </span>
        </el-dialog>
        <!--修改框-->
        <el-dialog title="修改" :visible.sync="updateVisible" width="30%" >
            <el-form  :model="updateform" :rules="updateformrules" class="demo-form-inline" ref="updateform">
                <el-form-item label="">
                    <el-input v-model="updateform.id" placeholder="id" type="hidden"></el-input>
                </el-form-item>
                <el-form-item label="部门编号" prop="sn">
                    <el-input v-model="updateform.sn" placeholder="部门编号"></el-input>
                </el-form-item>

                <el-form-item label="部门名" prop="name">
                    <el-input v-model="updateform.name" placeholder="部门名"></el-input>
                </el-form-item>

                <el-form-item label="部门经理">
                    <el-select v-model="updateform.managerId" placeholder="请选择">
                        <el-option
                                v-for="item in managerDepartmentOptions"
                                :key="item.id"
                                :label="item.username"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="上级部门">
                    <el-select v-model="updateform.parentId" placeholder="请选择">
                        <el-option
                                v-for="item in parentDepartmentOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>


                <el-form-item label="状态">
                    <el-radio-group v-model="updateform.state">
                        <el-radio  value="开启" :label=1>开启</el-radio>
                        <el-radio  value="禁用" :label=0>禁用</el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="updateVisible = false">取 消</el-button>
                <el-button type="primary"@click.native="updateSubmit" :loading="updateLoading">确 定</el-button>
            </span>
        </el-dialog>


    </section>
</template>

<script>

    export default {
        data() {
            return {
                filters: {
                    name: '',
                    state:""
                },
                department: [],
                total: 0,
                pageSize: 10,
                currentPage:1,
                listLoading: false,
                sels: [],//列表选中列
                //默认隐藏添加框
                dialogVisible : false,
                updateVisible: false,
                addform :{
                    sn: '',
                    name: '',
                    state: '',
                    managerId:"",
                    parentId:""
                },
                updateform: {
                    id: '',
                    sn: '',
                    name: '',
                    state: '',
                    managerId:"",
                    parentId:""
                },
                //添加的加载框
                addLoading: false,
                updateLoading: false,
                //项目经理列表默认值
                managerDepartmentOptions:[],
                //上级部门列表默认值
                parentDepartmentOptions:[],
                addformrules: {
                    sn: [
                        { required: true, message: '请输入部门编号', trigger: 'blur' }
                    ],
                    name: [
                        { required: true, message: '请输入部门名', trigger: 'blur' }
                    ]

                },
                updateformrules: {
                    sn: [
                        { required: true, message: '请输入部门编号', trigger: 'blur' }
                    ],
                    name: [
                        { required: true, message: '请输入部门名', trigger: 'blur' }
                    ]

                }



            }
        },
        methods: {
            //状态显示转换
            formatState: function (row, column) {
                return row.state == 1 ? '启用' : '禁用';
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.getDepartment();
            },
            //获取部门列表
            getDepartment() {
                this.listLoading = true;  //开启加载圈

                let param = {"currentPage": this.currentPage,
                    "pageSize": this.pageSize,
                    "name":this.filters.name,
                    "state":this.filters.state};
                this.$http.patch("/department",param).then((res=>{
                    //console.debug(res)
                    this.department = res.data.result
                    this.total = res.data.total
                }))
                this.listLoading = false;  //关闭加载圈
            },
            //删除
            handleDel: function (index, row) {
                //console.debug(row)
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //准备参数 传入id
                    let param = {"id":row.id};
                    //发送axios请求
                    this.$http.delete("/department/"+row.id,param).then((result=>{


                        //console.debug(result.data.success)
                        if(result.data.success){
                            this.$message({
                                type: 'success',
                                message: result.data.msg
                            });
                        }else {
                            this.$message.error(result.data.msg);
                        }
                        //删除后刷新列表
                        this.getDepartment()
                    }));
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },
            //显示编辑界面
            handleEdit: function (index, row) {
                console.debug(row)
                /*this.updateform = {
                    id:row.id,
                    sn:row.sn,
                    name:row.name,
                    state: row.state,
                    manager:row.manager,
                    parent:row.parent
                }*/
                //回显数据
                for(var k in row){
                    this.updateform[k] = row[k];
                }
                //如果上级部门有值，上级部门回显
                //console.debug(this.updateform)
                if(this.updateform.parent){
                    this.updateform.parentId = this.updateform.parent.id;
                }
                //如果部门经理有值 回显
                if(this.updateform.manager){
                    this.updateform.managerId = this.updateform.manager.id;
                }

                //显示对话框
                this.updateVisible = true;
            },
            //显示新增界面
            handleAdd: function () {
                // //清空表单下面的验证提示
                // this.$refs.addForm.resetFields();
                if(this.$refs.addform){
                    this.$refs.addform.resetFields();
                }
                //清空表单
                this.addform = {
                    sn: '',
                    name: '',
                    state: '',
                    managerId:"",
                    parentId:""
                }
                //弹出框
                this.dialogVisible = true;
            },
            //编辑
            updateSubmit: function () {

                this.$refs["updateform"].validate((valid) => {
                    if (valid) {
                        let param = Object.assign({}, this.updateform);
                        console.debug(param)
                        //封装上级部门对象
                        let parent = {
                            id: param.parentId
                        };
                        //给上级部门设置值
                        param.parent = parent;



                        //封装经理对象
                        let manager = {
                            id: param.managerId
                        };
                        //给经理设置值
                        param.manager = manager;
                        console.debug(param)

                        this.$http.post("/department",param).then((result=>{
                            if(result.data.success){
                                this.$message({
                                    type: 'success',
                                    message: result.data.msg
                                });
                            }else {
                                this.$message.error(result.data.msg);
                            }
                            //关闭修改\框
                            this.updateVisible = false;
                            //修改后刷新列表
                            this.getDepartment()
                        }))
                    } else {

                        return false;
                    }
                });

            },
            //新增
            addSubmit: function () {
               console.log( this.$refs)
                this.$refs.addform.validate((valid) => {
                    if (valid) {
                        let param = Object.assign({}, this.addform);
                        //封装上级部门对象
                        let parent = {
                            id: param.parentId
                        };
                        //给上级部门设置值
                        param.parent = parent;

                        //封装经理对象
                        let manager = {
                            id: param.managerId
                        };
                        //给经理设置值
                        param.manager = manager;

                        //console.debug(param)
                        this.$http.put("/department",param).then((result=>{

                            if(result.data.success){
                                this.$message({
                                    type: 'success',
                                    message: result.data.msg
                                });
                            }else {
                                this.$message.error(result.data.msg);
                            }
                            //关闭新增框
                            this.dialogVisible = false;
                            //新增后刷新列表
                            this.getDepartment()
                        }))
                    } else {
                        return false;
                    }
                });

            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {

                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //获取选中行的id，最终以数组展示
                    var ids = this.sels.map(item => item.id);//[1,2,3,4]
                    //发送axios请求
                    this.$http.patch("/department/batchRemove",ids).then((result=>{
                        //console.debug(result.data.success)
                        if(result.data.success){
                            this.$message({
                                type: 'success',
                                message: result.data.msg
                            });
                        }else {
                            this.$message.error(result.data.msg);
                        }
                        //删除后刷新列表
                        this.getDepartment()
                    }));
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //高级查询
            getSuperDepartment(){
                let param = Object.assign({}, this.filters);
                //console.debug(param)
                this.getDepartment()
            },
            //获取所有的部门经理
            loadAllManagerDepartments(){
                this.$http.patch("/employee/loadAll").then((res => {
                    console.debug(res)
                    this.managerDepartmentOptions = res.data;
                }));
            },
            //获取所有部门 (上级部门)
            loadAllParentDepartments(){
                this.$http.patch("/department/loadAll").then((res => {
                    this.parentDepartmentOptions = res.data;
                }));
            }

        },
        mounted() {
            this.getDepartment(),
            this.loadAllManagerDepartments(),
            this.loadAllParentDepartments()

        }
    }
</script>

